#!/bin/bash
# WSL 2 + Docker Engine 安装脚本
# 使用方法: 在WSL 2中运行此脚本

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

# 检查是否在WSL 2中运行
check_wsl2() {
    if [ ! -f /proc/version ] || ! grep -q Microsoft /proc/version; then
        print_error "此脚本需要在WSL 2中运行"
        print_info "请先安装WSL 2，然后在此环境中运行此脚本"
        exit 1
    fi
    
    print_success "检测到WSL 2环境"
}

# 更新系统包
update_system() {
    print_info "更新系统包..."
    sudo apt-get update
    sudo apt-get upgrade -y
    print_success "系统包更新完成"
}

# 安装Docker Engine
install_docker() {
    print_info "安装Docker Engine..."
    
    # 安装依赖
    sudo apt-get install -y \
        apt-transport-https \
        ca-certificates \
        curl \
        gnupg \
        lsb-release
    
    # 添加Docker官方GPG密钥
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
    
    # 添加Docker仓库
    echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
    
    # 安装Docker Engine
    sudo apt-get update
    sudo apt-get install -y docker-ce docker-ce-cli containerd.io
    
    # 启动Docker服务
    sudo systemctl start docker
    sudo systemctl enable docker
    
    # 将当前用户添加到docker组
    sudo usermod -aG docker $USER
    
    print_success "Docker Engine安装完成"
}

# 安装Docker Compose
install_docker_compose() {
    print_info "安装Docker Compose..."
    
    # 下载Docker Compose
    sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    
    # 设置执行权限
    sudo chmod +x /usr/local/bin/docker-compose
    
    print_success "Docker Compose安装完成"
}

# 验证安装
verify_installation() {
    print_info "验证Docker安装..."
    
    # 检查Docker版本
    docker --version
    docker-compose --version
    
    # 运行测试容器
    docker run hello-world
    
    if [ $? -eq 0 ]; then
        print_success "Docker安装验证成功"
    else
        print_error "Docker安装验证失败"
        exit 1
    fi
}

# 主函数
main() {
    print_info "开始安装Docker Engine (WSL 2环境)..."
    
    # 检查环境
    check_wsl2
    
    # 更新系统
    update_system
    
    # 安装Docker
    install_docker
    
    # 安装Docker Compose
    install_docker_compose
    
    # 验证安装
    verify_installation
    
    print_success "Docker Engine安装完成！"
    print_info ""
    print_info "使用方法:"
    print_info "  1. 重新登录WSL 2或运行: newgrp docker"
    print_info "  2. 运行: docker --version 验证安装"
    print_info "  3. 使用Docker编译FFmpeg"
    print_info ""
    print_warning "注意: 需要重新登录WSL 2才能使docker组权限生效"
}

# 执行主函数
main "$@"
